package com.example.demo.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一返回值处理
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired //依赖注入ObjectMapper,这是系统自带的,不用我们写什么,直接拿
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 已经包装好的对象
        if (body instanceof ResultAjax) { //为正确的格式,不用操作什么
            return body;
        }
        // 对字符串进行判断和处理
        if (body instanceof String) { //为string的时候
            ResultAjax resultAjax = ResultAjax.succ(body);//依赖string数据来构造返回类
            try {
                return objectMapper.writeValueAsString(resultAjax);//把返回类转换为json对象即可
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return ResultAjax.succ(body);//走到这里,说明返回类型不是ResultAjax),得调整,-->把传递来的数据当做参数构造ResultAjax类,传递回去
    }
}
